package com.finance.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.finance.entity.CouponRedeem;
import com.finance.mapper.CouponRedeemMapper;
import com.finance.service.CouponRedeemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * C06
 * 券回兑数据Service实现类
 */
@Slf4j
@Service
public class CouponRedeemServiceImpl extends ServiceImpl<CouponRedeemMapper, CouponRedeem> implements CouponRedeemService {

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm");

    @Override
    public int processOrders(List<Map<String, String>> records, String searchDate, boolean forceUpdate) {
        return processOrders(records, searchDate, forceUpdate, null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int processOrders(List<Map<String, String>> records, String searchDate, boolean forceUpdate, String cinemaId) {

        if (records == null || records.isEmpty()) {
            return 0;
        }

        // 如果不是强制更新，先检查数据是否存在
        if (!forceUpdate) {
            long count = lambdaQuery()
                    .eq(CouponRedeem::getSearchDate, searchDate)
                    .count();
            if (count > 0) {
                log.info("C06数据已存在，searchDate: {}, 跳过处理", searchDate);
                return 0;
            }
        } else {
            // 如果是强制更新，先删除指定日期的数据
            lambdaUpdate()
                    .eq(CouponRedeem::getSearchDate, searchDate)
                    .remove();
        }

        List<CouponRedeem> orderList = new ArrayList<>();
        for (Map<String, String> record : records) {
            try {
                CouponRedeem order = new CouponRedeem();
                order.setCinemaId(cinemaId);
                //回兑影院名称,回兑影院编码,回兑影院所属区域,回兑时间,订单号,兑换渠道,兑换渠道编码,券类型,券类型编码
                if (StringUtils.hasText(record.get("回兑影院名称"))) {
                    order.setRedeemCinemaName(record.get("回兑影院名称"));
                }
                if (StringUtils.hasText(record.get("回兑影院编码"))) {
                    order.setRedeemCinemaCode(record.get("回兑影院编码"));
                }
                if (StringUtils.hasText(record.get("回兑影院所属区域"))) {
                    order.setRedeemCinemaArea(record.get("回兑影院所属区域"));
                }
                // 转换日期时间
                String redeemTime = record.get("回兑时间");
                if (StringUtils.hasText(redeemTime)) {
                    order.setRedeemTime(LocalDateTime.parse(redeemTime, DATE_TIME_FORMATTER));
                }
                if (StringUtils.hasText(record.get("订单号"))) {
                    order.setOrderNo(record.get("订单号"));
                }
                if (StringUtils.hasText(record.get("兑换渠道"))) {
                    order.setRedeemChannel(record.get("兑换渠道"));
                }
                if (StringUtils.hasText(record.get("兑换渠道编码"))) {
                    order.setRedeemChannelCode(record.get("兑换渠道编码"));
                }
                if (StringUtils.hasText(record.get("券类型"))) {
                    order.setCouponType(record.get("券类型"));
                }
                if (StringUtils.hasText(record.get("券类型编码"))) {
                    order.setCouponTypeCode(record.get("券类型编码"));
                }
                // 券模版名称,券模版编码,自定义券分类,券来源编码,券批次,券码,券数量,券面值,券基础售价
                if (StringUtils.hasText(record.get("券模版名称"))) {
                    order.setCouponTemplateName(record.get("券模版名称"));
                }
                if (StringUtils.hasText(record.get("券模版编码"))) {
                    order.setCouponTemplateCode(record.get("券模版编码"));
                }
                if (StringUtils.hasText(record.get("自定义券分类"))) {
                    order.setCustomCouponCategory(record.get("自定义券分类"));
                }
                if (StringUtils.hasText(record.get("券来源编码"))) {
                    order.setCouponSourceCode(record.get("券来源编码"));
                }
                if (StringUtils.hasText(record.get("券批次"))) {
                    order.setCouponBatch(record.get("券批次"));
                }
                if (StringUtils.hasText(record.get("券码"))) {
                    order.setCouponCode(record.get("券码"));
                }
                // 转换数值类型
                String couponQuantity = record.get("券数量");
                if (StringUtils.hasText(couponQuantity)) {
                    order.setCouponQuantity(Integer.parseInt(couponQuantity));
                }
                String couponFaceValue = record.get("券面值");
                if (StringUtils.hasText(couponFaceValue)) {
                    order.setCouponFaceValue(new BigDecimal(couponFaceValue));
                }
                String couponBasePrice = record.get("券基础售价");
                if (StringUtils.hasText(couponBasePrice)) {
                    order.setCouponBasePrice(new BigDecimal(couponBasePrice));
                }
                // 券最大限额,商品订单金额,票房订单金额,卖品订单金额,券支付金额,券支付票房金额
                String couponMaxLimit = record.get("券最大限额");
                if (StringUtils.hasText(couponMaxLimit)) {
                    order.setCouponMaxLimit(new BigDecimal(couponMaxLimit));
                }
                String goodsOrderAmount = record.get("商品订单金额");
                if (StringUtils.hasText(goodsOrderAmount)) {
                    order.setGoodsOrderAmount(new BigDecimal(goodsOrderAmount));
                }
                String ticketOrderAmount = record.get("票房订单金额");
                if (StringUtils.hasText(ticketOrderAmount)) {
                    order.setTicketOrderAmount(new BigDecimal(ticketOrderAmount));
                }
                String snackOrderAmount = record.get("卖品订单金额");
                if (StringUtils.hasText(snackOrderAmount)) {
                    order.setSnackOrderAmount(new BigDecimal(snackOrderAmount));
                }
                String couponPayAmount = record.get("券支付金额");
                if (StringUtils.hasText(couponPayAmount)) {
                    order.setCouponPayAmount(new BigDecimal(couponPayAmount));
                }
                String couponPayTicketAmount = record.get("券支付票房金额");
                if (StringUtils.hasText(couponPayTicketAmount)) {
                    order.setCouponPayTicketAmount(new BigDecimal(couponPayTicketAmount));
                }
                // 券支付卖品金额,券价值减券支付,券售价减券支付,订单补差金额,补贴方
                String couponPaySnackAmount = record.get("券支付卖品金额");
                if (StringUtils.hasText(couponPaySnackAmount)) {
                    order.setCouponPaySnackAmount(new BigDecimal(couponPaySnackAmount));
                }
                String couponValueMinusPay = record.get("券价值减券支付");
                if (StringUtils.hasText(couponValueMinusPay)) {
                    order.setCouponValueMinusPay(new BigDecimal(couponValueMinusPay));
                }
                String couponPriceMinusPay = record.get("券售价减券支付");
                if (StringUtils.hasText(couponPriceMinusPay)) {
                    order.setCouponPriceMinusPay(new BigDecimal(couponPriceMinusPay));
                }
                String orderDiffAmount = record.get("订单补差金额");
                if (StringUtils.hasText(orderDiffAmount)) {
                    order.setOrderDiffAmount(new BigDecimal(orderDiffAmount));
                }
                if (StringUtils.hasText(record.get("补贴方"))) {
                    order.setSubsidyParty(record.get("补贴方"));
                }
                // 补贴金额,商品信息,放映日期,放映时间,影厅,发行时间,发券影院名称
                String subsidyAmount = record.get("补贴金额");
                if (StringUtils.hasText(subsidyAmount)) {
                    order.setSubsidyAmount(new BigDecimal(subsidyAmount));
                }
                if (StringUtils.hasText(record.get("商品信息"))) {
                    order.setGoodsInfo(record.get("商品信息"));
                }
                // 转换日期时间
                String showDate = record.get("放映日期");
                if (StringUtils.hasText(showDate)) {
                    order.setShowDate(LocalDate.parse(showDate, DATE_FORMATTER));
                }
                String showTime = record.get("放映时间");
                if (StringUtils.hasText(showTime)) {
                    order.setShowTime(LocalTime.parse(showTime, TIME_FORMATTER));
                }
                if (StringUtils.hasText(record.get("影厅"))) {
                    order.setHallName(record.get("影厅"));
                }
                String couponIssueTime = record.get("发行时间");
                if (StringUtils.hasText(couponIssueTime)) {
                    order.setCouponIssueTime(LocalDateTime.parse(couponIssueTime, DATE_TIME_FORMATTER));
                }
                if (StringUtils.hasText(record.get("发券影院名称"))) {
                    order.setIssueCinemaName(record.get("发券影院名称"));
                }
                // 发券影院编码,发券影院所属区域,操作员工号,操作员,券销售员工号,券销售员,发券影城所属区域编码
                if (StringUtils.hasText(record.get("发券影院编码"))) {
                    order.setIssueCinemaCode(record.get("发券影院编码"));
                }
                if (StringUtils.hasText(record.get("发券影院所属区域"))) {
                    order.setIssueCinemaArea(record.get("发券影院所属区域"));
                }
                if (StringUtils.hasText(record.get("操作员工号"))) {
                    order.setOperatorEmployeeNo(record.get("操作员工号"));
                }
                if (StringUtils.hasText(record.get("操作员"))) {
                    order.setOperator(record.get("操作员"));
                }
                if (StringUtils.hasText(record.get("券销售员工号"))) {
                    order.setCouponSaleEmployeeNo(record.get("券销售员工号"));
                }
                if (StringUtils.hasText(record.get("券销售员"))) {
                    order.setCouponSaleEmployee(record.get("券销售员"));
                }
                if (StringUtils.hasText(record.get("发券影城所属区域编码"))) {
                    order.setIssueCinemaAreaCode(record.get("发券影城所属区域编码"));
                }
                // 回兑影城所属区域编码,影厅编码,会员ID
                if (StringUtils.hasText(record.get("回兑影城所属区域编码"))) {
                    order.setRedeemCinemaAreaCode(record.get("回兑影城所属区域编码"));
                }
                if (StringUtils.hasText(record.get("影厅编码"))) {
                    order.setHallCode(record.get("影厅编码"));
                }
                if (StringUtils.hasText(record.get("会员ID"))) {
                    order.setMemberId(record.get("会员ID"));
                }
                // 设置新增字段
                if (StringUtils.hasText(record.get("券码有效期"))) {
                    order.setCouponValidityPeriod(record.get("券码有效期"));
                }
                if (StringUtils.hasText(record.get("流向客户名称"))) {
                    order.setCustomerName(record.get("流向客户名称"));
                }
                if (StringUtils.hasText(record.get("流向客户外部编码"))) {
                    order.setCustomerExternalCode(record.get("流向客户外部编码"));
                }
                // 设置searchDate
                order.setSearchDate(searchDate);
                //TODO 缺少字段：券码有效期,流向客户名称,流向客户外部编码


                orderList.add(order);
            } catch (Exception e) {
                log.error("处理券回兑记录失败: {}", record, e);
            }
        }

        try {
            if (!orderList.isEmpty()) {
                return saveBatch(orderList) ? orderList.size() : 0;
            }
            return 0;
        } catch (Exception e) {
            log.error("批量保存券回兑数据失败", e);
            throw e;
        }
    }

}